import 'dart:math';

class RandomUtil {
  ///随机生成密码
  String randomPassword(int length,
      {bool hasNumber = true, bool hasLetter = true, bool hasSymbol = true}) {
    int n = hasNumber ? 1 : 0;
    int l = hasLetter ? 1 : 0;
    int s = hasSymbol ? 1 : 0;

    if (length < (n + l + s)) {
      return "";
    }

    if (n == l && l == s && s == 0) {
      return "";
    }

    if (l == s && l == 0) {
      return _random(length, _numbers);
    }

    if (n == l && n == 0) {
      return _random(length, _symbols);
    }

    if (n == s && n == 0) {
      return _random(length, _letters);
    }

    if (n == 0) {
      l = l + Random().nextInt(length - s);
      s = length - l;
    } else if (l == 0) {
      n = n + Random().nextInt(length - s);
      s = length - n;
    } else if (s == 0) {
      n = n + Random().nextInt(length - l);
      l = length - n;
    } else {
      n = n + Random().nextInt(length - (l + s));
      l = l + Random().nextInt(length - (n + s));
      s = length - (n + l);
    }
    String normal =
        _random(n, _numbers) + _random(l, _letters) + _random(s, _symbols);
    return _randomIndex(normal);
  }

  /// 乱序字符串
  String _randomIndex(String origin) {
    List<String> newStr = origin.split("");
    for (int i = 0; i < newStr.length; i++) {
      int _c = Random().nextInt(newStr.length);
      String _s = newStr[_c];
      newStr[_c] = newStr[i];
      newStr[i] = _s;
    }
    return newStr.join("");
  }

  ///随机生成字符
  String _random(int length, List<String> origins) {
    String a = "";
    for (int i = 0; i < length; i++) {
      a += origins[Random().nextInt(origins.length)];
    }
    return a;
  }

  final List<String> _letters = [
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y",
    "z"
  ];
  final List<String> _numbers = [
    "0",
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9"
  ];
  final List<String> _symbols = ["_", "@", "#", "&"];
}
